#! /usr/bin/env python3
#**************************************************************************************#
#     .--.                                                                             #
#    |o_o |                                                                            #
#    |:_/ |    Copyright (C) 2006 ~ 2011 Triductor Technology Inc.                     # 
#   //   \ \                All Rights Reserved Worldwide                              #
#  (|     | )                                                                          #
# /'\_   _/`\                                                                          #
# \___)=(___/                                                                          #
#**************************************************************************************#
#                                                                                      #
# Filename     : cmd.py
#                                                                                      #   
# Version      : $Revision: 1.0 $                                                      #
# Author       : Eric Lee (eric@triductor.com)                                         #
#                                                                                      #
# Created      : Thu Jun 23 09:37:07 2011
#                                                                                      #
# Module(s)    : Python 3                                                              #
#**************************************************************************************#
#--------------------------------------------------------#
# Description                                            #
#--------------------------------------------------------#
"""
    Parse the netlist to get the cells' hierarchical structure, 
and generate the cells list or force-operation file to initialize
cells for Gate-Level Simulation
"""

#--------------------------------------------------------#
# Revision                                               #
#--------------------------------------------------------#
__version__ = "$Revision: 1.0 $"

#--------------------------------------------------------#
# Import modules                                         #
#--------------------------------------------------------#
import argparse
import logging
import os
import sys
#import re
#import shutil
#import copy
#import tempfile
#import string
#import configparser
#import math
#import decimal
#from   elementtree import ElementTree as ET
#import multiprocessing as MP

#Import cmd's Command Lib
#from Cmds import *

#--------------------------------------------------------#
# Gloabl Variables Declarations                          #
#--------------------------------------------------------#

# create module-level logger
mlog = logging.getLogger(__name__)

#--------------------------------------------------------#
# Class     Definition                                   #
#--------------------------------------------------------#
                

#--------------------------------------------------------#
# Functions Definition                                   #
#--------------------------------------------------------#
#--------------------------------------------------------#
# get_cmd_list()    Definition                           #
#--------------------------------------------------------#
def get_cmd_list():
    import glob
    cmd_list = "Commands List:\n   help\n"
    for i in glob.glob(os.path.dirname(os.path.realpath(sys.argv[0])) + "/Cmds/Cmd*.py"):
        i = os.path.basename(i)[:-3]
        i = i[3:].lower()
        if i != 'base':
            cmd_list += "   " + i  + "\n"

    return cmd_list

#--------------------------------------------------------#
# parse_args()    Definition                             #
#--------------------------------------------------------#
#
desc        = __doc__
epilog      = get_cmd_list()
args_parser = argparse.ArgumentParser(description=desc, epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter)

def parse_args():
    """Parse the Arguments of Command-line

       Return Arguments 
    """
    #-----------------------------------------
    #Add options
    #-----------------------------------------
    """
    add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])?
        * name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo
        * action        - The basic type of action to be taken when this argument is encountered at the command-line.
                           + 'store'        - This just stores the argument's value.(default action)
                           + 'store_const'  - This stores the value specified by the const keyword
                           + 'store_true' and 'store_false' - These store the values True and False respectively.
                           + 'append'       - This stores a list, and appends each argument value to the list.
                           + 'append_const' - This stores a list, and appends the value specified by the const keyword argument to the list.
                           + 'version'      - This is the version info.
        * nargs         - The number of command-line arguments that should be consumed.
        * const         - A constant value required by some action and nargs selections.
        * default       - The value produced if the argument is absent from the command-line.
        * type          - The type to which the command-line arg should be converted.
        * choices       - A container of the allowable values for the argument.
        * required      - Whether or not the command-line option may be omitted (optionals only).
        * help          - A brief description of what the argument does.
        * metavar       - A name for the argument in usage messages.
        * dest          - The name of the attribute to be added to the object returned by parse_args().
    """

    #-----------------------------------------
    #Add version and logging argument
    #-----------------------------------------
    args_parser.add_argument('-v', '--version', action='version', version=__version__)
    args_parser.add_argument('-l', '--log',     dest  ='log'    , default='info',
                        choices=['debug', 'info', 'warning', 'error', 'fatal', 'critical'],
                        help="Specify the logging severity-level, default: info")

    #-----------------------------------------
    #TODO: Add user-defined options
    #-----------------------------------------
    args_parser.add_argument('cmd',            nargs =1,                              help='Specify the input RTL file(s) to parse.' )

    #-----------------------------------------
    ##Parse arguments
    #-----------------------------------------
    (args, left_args) = args_parser.parse_known_args()

    #-----------------------------------------
    #Post-Process of arguments
    #-----------------------------------------

    #-----------------------------------------
    #Set the severity-level
    #-----------------------------------------
    args.log = getattr(logging, args.log.upper(), None)
    logging.basicConfig(level =args.log,
                        format="\n\033[34m%(levelname)s: %(pathname)s #%(lineno)d: %(name)s:\033[0m\n%(message)s"
                       )

    return (args, left_args) 


#--------------------------------------------------------#
# run_help()    Definition                               #
#--------------------------------------------------------#
def run_help(left_args):
    """Run all the imported geneators which named as 'GenXXXX'.py in the Generator dir to generate the all types files

    Arguments:
        gen_proj_file_en:  Enable to geneate project's files(project html, C/Verilog Header list, etc.).

        Note:  1. The generates should be put in 'Generator' dir and included by __init__.py
               2. The name of generates should start with 'Gen'
               3. The generates should have a method(attribution) named "gen_proj"
    """

    subargs_parser = argparse.ArgumentParser()
    subargs_parser.add_argument('cmd',  nargs ='*')
    subargs = subargs_parser.parse_known_args(left_args)[0]

    if len(subargs.cmd) == 0:
        args_parser.print_help()
        sys.exit(1)

    cmd_name = subargs.cmd[0]

    cmd = """\
try:            
    from Cmds import Cmd{mod_name}
except ImportError:
    mlog.fatal("Illegal Command Name: {cmd}\\n")
    args_parser.print_help()
    sys.exit(1)

Cmd{mod_name}.args_parser.print_help() 
""".format(cmd=cmd_name, mod_name=cmd_name.title())

    mlog.debug(cmd)

    exec(cmd)

    #Terminate the program
    sys.exit(0)

#--------------------------------------------------------#
# run_cmd()    Definition                                #
#--------------------------------------------------------#
def run_cmd(args, left_args):
    """Run all the imported geneators which named as 'GenXXXX'.py in the Generator dir to generate the all types files

    Arguments:
        gen_proj_file_en:  Enable to geneate project's files(project html, C/Verilog Header list, etc.).

        Note:  1. The generates should be put in 'Generator' dir and included by __init__.py
               2. The name of generates should start with 'Gen'
               3. The generates should have a method(attribution) named "gen_proj"
    """

    cmd_name = args.cmd[0]

    if cmd_name == 'help':
        run_help(left_args)

    cmd = """\
try:            
    from Cmds import Cmd{mod_name}
except ImportError:
    mlog.fatal("Illegal Command Name: {cmd}\\n")
    args_parser.print_help()
    sys.exit(1)

Cmd{mod_name}.cmd.run(left_args)
""".format(cmd=cmd_name, mod_name=cmd_name.title())

    mlog.debug(cmd)

    exec(cmd)


#--------------------------------------------------------#
# main()    Definition                                   #
#--------------------------------------------------------#
def main():
    """The main process of program"""

    #--------------------------------------
    #Parse the arguments
    #--------------------------------------
    (args, left_args) = parse_args()

    #--------------------------------------
    #Run Command
    #--------------------------------------
    run_cmd(args, left_args)


#--------------------------------------------------------#
# Main  Process                                          #
#--------------------------------------------------------#
if __name__ == "__main__":
    main()



#**************************************************************************************#
# vim:noma:ft=python:fdm=marker:nowrap  
